<?php
namespace Modules\ShopApi\Http\Controllers\v1;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use zgldh\QiniuStorage\QiniuStorage;
use Modules\AuthAdmin\Models\AuthImage as AuthImageModel;
use Modules\AuthAdmin\Models\AuthConfig as AuthConfigModel;
use Modules\AuthAdmin\Services\CommonService;
class UploadController extends CommonController
{ 
	/**
	 * @name  单图上传
	 * @method  POST	
	 * @return  JSON	
	 */
	public function upload_file(Request $request){
    	if ($request->isMethod('POST')){
    		$fileCharater = $request->file('file');
    		if ($fileCharater->isValid()){
				$config = (new AuthConfigModel())->config_info_data();
				if($config['image_status'] == 1){
					$path = $request->file('file')->store(date('Ymd'),'shop_upload');
					if ($path){
						$url = '/shop_upload/images/'.$path;
					}	
				}else if($config['image_status'] == 2){
					$url = $this->add_qiniu($fileCharater);
				}
				if(isset($url)){
					$image_id = AuthImageModel::insertGetId([
						'url'=>$url,
						'open'=>$config['image_status'],
						'status'=>0,
						'created_at'=> date('Y-m-d H:i:s')
					]);
					if($image_id){
						if($config['image_status'] == 1){
							$url = (new CommonService())->get_http_type().$url;
						}
						return (new AuthImageModel())->api_success([
							'msg' => '上传成功！',
							'data'=>[
								'image_id'=>$image_id,
								'url'=> $url
							]
						]);
					}
				}		
			}
			return (new AuthImageModel())->api_error([
				'msg' => '上传失败！',
			]);
    	}
    }
	/**
	 * @name 七牛云图片上传
	 * @param fileCharater 图片对象
	 * @return 返回上传路径
	 */
	//
	private function add_qiniu($fileCharater){
		// 初始化
		$disk = QiniuStorage::disk('qiniu');
		// 重命名文件
		$fileName = md5($fileCharater->getClientOriginalName().time().rand()).'.'.$fileCharater->getClientOriginalExtension();
		 // 上传到七牛
		$bool = $disk->put('iwanli/image_'.$fileName,file_get_contents($fileCharater->getRealPath()));
		// 判断是否上传成功
		if($bool){
			return $disk->downloadUrl('iwanli/image_'.$fileName);  
		}else{
			return false;
		}
	}
}
